<?php
/**
 * Created by PhpStorm.
 * User: Administratorjing
 * Date: 2018/7/19/019
 * Time: 23:48
 * by Hedy<714195347@qq.com>
 */

namespace App\Http\Controllers;


use App\Exceptions\InvalidRequestException;
use App\Models\User;
use App\Notifications\EmailVerificationNotification;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\Cache;

class EmailVerificationController extends Controller
{
    public function verify(Request $request)
    {
        //从url中获取 email 和 token 两个参数
        $email = $request->input('email');
        $token = $request->input('token');
        //如果其中一个为空说明不是一个合法的链接，直接抛出异常
        if(!$email || !$token){
            //throw new Exception('验证链接不正确');
            //更换成我们定义的
            throw new InvalidRequestException('验证链接不正确');
        }
        //从缓存中读取数据，我们把从url中获取的token与缓存中的值对比
        //如果缓存不存在或者返回的值与url中的token不一致就抛出异常
        if($token != Cache::get('email_verification_'.$email)){
            //throw new Exception('验证链接不正确或者已经过期😭');
            throw new InvalidRequestException('验证链接不正确或者已经过期😭');
        }
        //根据邮箱从数据库中获取对应的用户，需要判读用户是否存在
        if(!$user = User::where('email',$email)->first()){
           // throw new Exception('用户不存在≧ ﹏ ≦');
            throw new InvalidRequestException('用户不存在≧ ﹏ ≦');
        }
        //将指定的key从缓存中删除，由于完成验证，不需要保留
        Cache::forget('email_verification_'.$email);
        //把对应用户的email_verified字段改为true
        $user->update(['email_verified'=>true]);
        //邮箱验证成功
        return view('pages.success',['msg'=>'邮箱验证成功']);
    }

    /**
     * 用户主动请求邮箱激活
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws Exception
     */
    public function send(Request $request)
    {
        $user = $request->user();
        //判断用户是否已经激活
        if($user->email_verified){
           // throw new Exception('亲，您已经验证过邮箱了');
            throw new InvalidRequestException('亲，您已经验证过邮箱了');
        }
        //调用notify()方法用来发送我们定义好的通知类
        $user->notify(new EmailVerificationNotification());
        return view('pages.success',['msg'=>'邮件发送成功']);

    }

}